/**
 * Copyright (c) 2006 George Malamidis, nutrun.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * $Author$
 * $Rev$
 */

package aerie.servlet;

import aerie.context.AerieContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UriParser {
    private AerieContext context;
    private List tokens = new ArrayList();

    public UriParser(String uri, AerieContext context) {
        this.context = context;
        this.tokens = Arrays.asList(parse(uri, context).split("/"));
    }

    public String extractController() {
        String controller = "";
        String path = context.path.equals("") ? context.path : context.path + "/";

        if (tokens.size() > 1) {
            controller = tokens.get(1).toString().toLowerCase();
        }

        if ("".equals(controller) || null == controller) {
            controller = context.welcomeController;
        }
        return path + controller;
    }

    public String extractAction() {
        return tokens.size() > 2 ? tokens.get(2).toString() : "index";
    }

    public String extractParameter() {
        return (String) (tokens.size() > 3 ? tokens.get(3) : null);
    }

    private String parse(String uri, AerieContext context) {
        return uri.replaceFirst(context.path, "")
                .replaceFirst(context.webAppContext, "")
                .replaceAll("//", "/")
                .trim();
    }
}
